<template>
  <div class="voice-select">
    <el-select
      v-model="selectedValue"
      :placeholder="placeholder"
      filterable
      clearable
      remote
      :remote-method="handleRemoteSearch"
      :loading="loading"
      @change="handleSelectChange"
      style="width: 100%"
    >
      <el-option
        v-for="item in voiceOptions"
        :key="item.value"
        :value="item.value"
        :label="item.label"
      >
        <div class="voice-option">
          <span class="voice-text" :title="item.label">{{ truncateText(item.label, 30) }}</span>
          <div class="voice-actions">
            <el-button
              type="text"
              size="small"
              @click.stop="playVoice(item)"
              :loading="playingVoiceId === item.value"
              class="play-btn"
            >
              <el-icon><VideoPlay /></el-icon>
            </el-button>
          </div>
        </div>
      </el-option>
      <el-option
        label="+ 创建新语音"
        value="__create_new__"
        style="color: #409eff; font-weight: bold;"
      />
    </el-select>
    
    <!-- 创建新语音对话框 -->
    <el-dialog
      v-model="createDialogVisible"
      :title="dialogTitle"
      width="500px"
      @close="resetCreateForm"
    >
      <el-form
        ref="createFormRef"
        :model="createForm"
        :rules="createFormRules"
        label-width="80px"
      >
        <el-form-item label="语音类型" prop="type">
          <el-select v-model="createForm.type" disabled style="width: 100%">
            <el-option
              :label="audioTypeLabel"
              :value="audioType"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="文件内容" prop="text">
          <el-input
            v-model="createForm.text"
            type="textarea"
            :rows="4"
            :maxlength="1000"
            show-word-limit
            placeholder="请输入语音文本内容"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreateVoice" :loading="creating">
          创建
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { VideoPlay } from '@element-plus/icons-vue'
import { create as createVoice } from '@/plugins/ai-warning/file/api/rdFileVoice.ts'
import { page as getVoiceList } from '@/plugins/ai-warning/file/api/rdFileVoice.ts'
import { getFullFileUrl } from '@/utils/fileUrl'
import { useAudioManager } from '@/plugins/ai-warning/file/views/rdFileVoice/composables/useAudioManager'

interface Props {
  modelValue?: number | string
  placeholder?: string
  audioType: number // 1: 设备预警语音, 3: 提示语音
  apiParams?: any
  onVoiceSelected?: (voiceData: any) => void
}

interface Emits {
  (e: 'update:modelValue', value: number | string): void
  (e: 'change', value: number | string): void
  (e: 'voice-selected', voiceData: { id: number | string, text: string }): void
}

const props = withDefaults(defineProps<Props>(), {
  placeholder: '请选择语音',
  apiParams: () => ({ page: 1, pageSize: 1000 })
})

const emit = defineEmits<Emits>()

const selectedValue = ref<number | string>('')
const voiceOptions = ref<Array<{ label: string; value: number; file?: string }>>([])
const createDialogVisible = ref(false)
const creating = ref(false)
const loading = ref(false)
const playingVoiceId = ref<number | null>(null)
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const audioManager = useAudioManager()

const createFormRef = ref()
const createForm = ref({
  type: props.audioType,
  text: ''
})

const createFormRules = {
  text: [
    { required: true, message: '请输入语音文本内容', trigger: 'blur' },
    { min: 1, max: 1000, message: '文本长度在 1 到 1000 个字符', trigger: 'blur' }
  ]
}

const audioTypeLabel = computed(() => {
  return props.audioType === 1 ? '设备预警语音' : '提示语音'
})

const dialogTitle = computed(() => {
  return `创建${audioTypeLabel.value}`
})

// 根据ID获取对应的文本
const getVoiceTextById = (id: number | string) => {
  const voice = voiceOptions.value.find(item => item.value === id)
  return voice ? voice.label : ''
}


// 监听 modelValue 变化
watch(() => props.modelValue, (newVal) => {
  selectedValue.value = newVal || ''
}, { immediate: true })

// 监听 selectedValue 变化
watch(selectedValue, (newVal) => {
  emit('update:modelValue', newVal)
  emit('change', newVal)
})

// 加载语音列表
const loadVoiceList = async (keyword = '', page = 1) => {
  try {
    loading.value = true
    const params: any = {
      page,
      pageSize: pageSize.value,
      type: props.audioType
    }
    
    // 只有当有搜索关键词时才添加text字段
    if (keyword && keyword.trim()) {
      params.text = keyword.trim()
    }
    
    const response = await getVoiceList(params)
    
    console.log('语音列表API响应:', response)
    
    if (response.code === 200 && response.data) {
      console.log('语音列表数据:', response.data)
      voiceOptions.value = response.data.list.map((item: any) => ({
        label: item.text || '无内容',
        value: item.id,
        file: item.file
      }))
      total.value = response.data.total || 0
      currentPage.value = page
      console.log('处理后的语音选项:', voiceOptions.value)
    } else {
      console.log('API响应异常:', response)
    }
  } catch (error) {
    console.error('加载语音列表失败:', error)
    ElMessage.error('加载语音列表失败')
  } finally {
    loading.value = false
  }
}

// 远程搜索处理
const handleRemoteSearch = (keyword: string) => {
  searchKeyword.value = keyword
  loadVoiceList(keyword, 1)
}

// 处理选择变化
const handleSelectChange = (value: number | string) => {
  if (value === '__create_new__') {
    createDialogVisible.value = true
    selectedValue.value = ''
  } else {
    selectedValue.value = value
    
    // 找到选中的语音选项，获取其文本内容
    const selectedOption = voiceOptions.value.find(option => option.value === value)
    if (selectedOption && selectedOption.label) {
      // 触发change事件，传递语音数据
      emit('change', value)
      emit('update:modelValue', value)
      
      // 触发自定义事件，传递语音文本
      emit('voice-selected', {
        id: value,
        text: selectedOption.label
      })
      
      // 调用父组件传入的回调
      if (props.onVoiceSelected) {
        props.onVoiceSelected({
          id: value,
          text: selectedOption.label
        })
      }
    }
  }
}

// 创建新语音
const handleCreateVoice = async () => {
  if (!createFormRef.value) return
  
  try {
    await createFormRef.value.validate()
    creating.value = true
    
      const response = await createVoice(createForm.value)
      if (response.code === 200) {
        ElMessage.success('语音创建成功')
        createDialogVisible.value = false
        
        // 重新加载语音列表
        await loadVoiceList()
        
        // 设置新创建的语音为选中状态
        selectedValue.value = response.data.id
        
        // 触发voice-selected事件，传递新创建的语音数据
        const voiceData = {
          id: response.data.id,
          text: response.data.text || createForm.value.text
        }
        emit('voice-selected', voiceData)
        
        // 调用父组件传入的回调
        if (props.onVoiceSelected) {
          props.onVoiceSelected(voiceData)
        }
      } else {
        ElMessage.error(response.message || '语音创建失败')
      }
  } catch (error) {
    console.error('创建语音失败:', error)
    ElMessage.error('语音创建失败')
  } finally {
    creating.value = false
  }
}

// 重置创建表单
const resetCreateForm = () => {
  createForm.value.text = ''
  createFormRef.value?.clearValidate()
}

// 截断文本
const truncateText = (text: string, maxLength: number) => {
  if (text.length <= maxLength) return text
  return text.substring(0, maxLength) + '...'
}

// 播放语音
const playVoice = async (voice: { label: string; value: number; file?: string }) => {
  if (!voice.file) {
    ElMessage.warning('该语音没有音频文件')
    return
  }

  try {
    playingVoiceId.value = voice.value
    
    // 获取完整的音频URL
    const fullAudioUrl = getFullFileUrl(voice.file)
    
    // 创建音频元素
    const audio = new Audio(fullAudioUrl)
    audio.preload = 'metadata'
    
    // 生成唯一的实例ID
    const instanceId = `voice-select-${voice.value}-${Date.now()}`
    
    // 注册音频播放（会自动暂停其他音频）
    audioManager.registerAudioPlay(audio, instanceId)
    
    // 播放音频
    await audio.play()
    
    // 监听播放结束
    audio.addEventListener('ended', () => {
      playingVoiceId.value = null
      audioManager.unregisterAudioPlay(instanceId)
    })
    
    // 监听播放错误
    audio.addEventListener('error', (e) => {
      console.error('音频播放失败:', e)
      ElMessage.error('音频播放失败')
      playingVoiceId.value = null
      audioManager.unregisterAudioPlay(instanceId)
    })
    
  } catch (error) {
    console.error('播放语音失败:', error)
    ElMessage.error('语音播放失败')
    playingVoiceId.value = null
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadVoiceList('', 1)
})
</script>

<style scoped>
.voice-select {
  width: 100%;
}

.voice-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding: 4px 0;
}

.voice-text {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-right: 8px;
  font-size: 14px;
}

.voice-actions {
  display: flex;
  align-items: center;
  flex-shrink: 0;
}

.play-btn {
  padding: 4px 8px;
  min-width: auto;
  height: 24px;
  font-size: 12px;
}

.play-btn:hover {
  color: #409eff;
}

/* 优化下拉选项的样式 */
:deep(.el-select-dropdown__item) {
  padding: 8px 12px;
  height: auto;
  min-height: 34px;
}

:deep(.el-select-dropdown__item:hover) {
  background-color: #f5f7fa;
}

:deep(.el-select-dropdown__item.is-selected) {
  background-color: #ecf5ff;
  color: #409eff;
}
</style>
